<?php

namespace App\Task;

use Hyperf\Task\Annotation\Task;
use Memcached;
use function Hyperf\Config\config;

class MemcacheTask
{
    private static int $expiration = 0;

    private ?Memcached $manager = null;

    protected function manager()
    {
        if ($this->manager instanceof Memcached) {
            return $this->manager;
        }
        $memcacheConfigArray = config('memcache');
        self::$expiration = $memcacheConfigArray['mem_expiration'];
        $memcache = new Memcached($memcacheConfigArray['mem_name']);
        $memcache->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
        if (!count($memcache->getServerList())) {
            $memcache->addServers($memcacheConfigArray['mem_db']);
        }
        return $this->manager = $memcache;

    }

    #[Task]
    public function add($key, $value, $expiration = 0)
    {
        return $this->manager()->add($key, $value, $expiration ?? self::$expiration);
    }

    #[Task]
    public function set($key, $value, $expiration = 0)
    {
        return $this->manager()->set($key, $value, $expiration ?? self::$expiration);
    }

    #[Task]
    public function delete($key)
    {
        return $this->manager()->delete($key);
    }

    #[Task]
    public function get($key)
    {
        return $this->manager()->get($key);
    }

    #[Task]
    public function increment($key, $value)
    {
        return $this->manager()->increment($key, $value);
    }

    #[Task]
    public function decrement($key, $value)
    {
        return $this->manager()->decrement($key, $value);
    }

    #[Task]
    public function addLock($key, $expireTime = 2)
    {
        if ($this->manager()->add($key, 1, $expireTime ?? self::$expiration)) {
            return true;
        }
        return false;
    }

    #[Task]
    public function replace($key, $value, $expiration = null)
    {
        return $this->manager()->replace($key, $value, $expiration ?? self::$expiration);
    }

}